#!/bin/bash
# -*- coding: utf-8 -*-
# 新闻日报系统快速安装脚本

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 打印横幅
print_banner() {
    echo "============================================================"
    echo "📰 MorningByte 新闻日报系统 - 快速安装"
    echo "============================================================"
    echo "安装时间: $(date '+%Y-%m-%d %H:%M:%S')"
    echo "============================================================"
}

# 检查系统环境
check_system() {
    print_info "检查系统环境..."
    
    # 检查操作系统
    if [[ "$OSTYPE" == "darwin"* ]]; then
        OS="macOS"
    elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
        OS="Linux"
    elif [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]]; then
        OS="Windows"
    else
        OS="Unknown"
    fi
    
    print_success "检测到操作系统: $OS"
}

# 检查Python环境
check_python() {
    print_info "检查Python环境..."
    
    if command -v python3 &> /dev/null; then
        PYTHON_CMD="python3"
        PIP_CMD="pip3"
    elif command -v python &> /dev/null; then
        PYTHON_CMD="python"
        PIP_CMD="pip"
    else
        print_error "未找到Python环境"
        print_info "请先安装Python 3.7或更高版本:"
        echo "  macOS: brew install python3"
        echo "  Ubuntu/Debian: sudo apt install python3 python3-pip"
        echo "  CentOS/RHEL: sudo yum install python3 python3-pip"
        echo "  Windows: 从 https://python.org 下载安装"
        exit 1
    fi
    
    # 检查Python版本
    PYTHON_VERSION=$($PYTHON_CMD --version 2>&1 | cut -d' ' -f2)
    print_success "找到Python版本: $PYTHON_VERSION"
    
    # 检查pip
    if ! command -v $PIP_CMD &> /dev/null; then
        print_warning "未找到pip，正在安装..."
        $PYTHON_CMD -m ensurepip --upgrade
    fi
}

# 安装依赖包
install_dependencies() {
    print_info "安装Python依赖包..."
    
    if [ -f "requirements.txt" ]; then
        $PIP_CMD install -r requirements.txt
        print_success "依赖包安装完成"
    else
        print_error "未找到requirements.txt文件"
        exit 1
    fi
}

# 创建必要目录
create_directories() {
    print_info "创建必要目录..."
    
    mkdir -p logs
    mkdir -p data
    mkdir -p backups
    
    print_success "目录创建完成"
}

# 设置文件权限
set_permissions() {
    print_info "设置文件权限..."
    
    # 设置脚本执行权限
    chmod +x start.sh
    chmod +x stop.sh
    chmod +x check.sh
    
    print_success "权限设置完成"
}

# 创建系统服务（可选）
create_system_service() {
    print_info "是否创建系统服务？(y/n)"
    read -r create_service
    
    if [[ $create_service =~ ^[Yy]$ ]]; then
        print_info "创建系统服务..."
        
        # 获取当前目录
        CURRENT_DIR=$(pwd)
        USER_NAME=$(whoami)
        
        # 创建systemd服务文件
        if command -v systemctl &> /dev/null; then
            sudo tee /etc/systemd/system/morningbyte-news.service > /dev/null <<EOF
[Unit]
Description=MorningByte News Daily Service
After=network.target

[Service]
Type=simple
User=$USER_NAME
WorkingDirectory=$CURRENT_DIR
ExecStart=$CURRENT_DIR/start.sh
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF
            
            sudo systemctl daemon-reload
            sudo systemctl enable morningbyte-news.service
            
            print_success "系统服务创建完成"
            print_info "服务管理命令:"
            echo "  启动服务: sudo systemctl start morningbyte-news"
            echo "  停止服务: sudo systemctl stop morningbyte-news"
            echo "  查看状态: sudo systemctl status morningbyte-news"
            echo "  查看日志: sudo journalctl -u morningbyte-news -f"
        else
            print_warning "未找到systemctl，跳过系统服务创建"
        fi
    fi
}

# 运行初始配置
run_initial_setup() {
    print_info "运行初始配置..."
    
    if [ -f "setup_email.py" ]; then
        print_info "启动邮箱配置向导..."
        $PYTHON_CMD setup_email.py
    else
        print_warning "未找到配置脚本，请手动配置email_config.py"
    fi
}

# 显示安装完成信息
show_completion_info() {
    print_success "安装完成！"
    echo ""
    echo "============================================================"
    echo "📋 使用说明"
    echo "============================================================"
    echo "1. 启动服务:"
    echo "   ./start.sh"
    echo ""
    echo "2. 停止服务:"
    echo "   ./stop.sh"
    echo ""
    echo "3. 检查状态:"
    echo "   ./check.sh"
    echo ""
    echo "4. 重新配置:"
    echo "   $PYTHON_CMD setup_email.py"
    echo ""
    echo "5. 测试功能:"
    echo "   $PYTHON_CMD quick_test.py"
    echo ""
    echo "6. 查看日志:"
    echo "   tail -f logs/scheduler_\$(date +%Y%m%d).log"
    echo ""
    echo "============================================================"
    echo "💡 提示:"
    echo "- 服务将在每天指定时间自动发送新闻日报"
    echo "- 按 Ctrl+C 可以停止服务"
    echo "- 日志文件保存在 logs/ 目录中"
    echo "============================================================"
}

# 主函数
main() {
    print_banner
    
    # 检查环境
    check_system
    check_python
    
    # 安装依赖
    install_dependencies
    
    # 创建目录和设置权限
    create_directories
    set_permissions
    
    # 运行初始配置
    run_initial_setup
    
    # 创建系统服务（可选）
    create_system_service
    
    # 显示完成信息
    show_completion_info
}

# 运行主函数
main "$@"
